package com.desktop.android.launch

import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView

/**
 * 实现图标拖拽和交换功能
 */
class ItemTouchHelperCallback(
    private val onItemMove: (fromPosition: Int, toPosition: Int) -> Boolean,
    private val onDragStart: () -> Unit,
    private val onDragEnd: () -> Unit
) : ItemTouchHelper.Callback() {

    // 允许拖拽和滑动
    override fun getMovementFlags(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder
    ): Int {
        val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN or
                ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
        val swipeFlags = 0 // 不允许滑动删除
        return makeMovementFlags(dragFlags, swipeFlags)
    }

    // 处理拖拽时的位置交换
    override fun onMove(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder,
        target: RecyclerView.ViewHolder
    ): Boolean {
        // 通知适配器位置已交换
        return onItemMove(viewHolder.adapterPosition, target.adapterPosition)
    }

    // 处理滑动事件（这里不实现）
    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
        // 不处理滑动
    }

    // 拖拽开始时的回调
    override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
        super.onSelectedChanged(viewHolder, actionState)
        if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
            // 拖拽开始，放大视图并降低透明度
            viewHolder?.itemView?.alpha = 0.5f
            viewHolder?.itemView?.scaleX = 1.1f
            viewHolder?.itemView?.scaleY = 1.1f
            onDragStart()
        }
    }

    // 拖拽结束时的回调
    override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
        super.clearView(recyclerView, viewHolder)
        // 恢复视图状态
        viewHolder.itemView.alpha = 1.0f
        viewHolder.itemView.scaleX = 1.0f
        viewHolder.itemView.scaleY = 1.0f
        onDragEnd()
    }

    // 允许长按启动拖拽
    override fun isLongPressDragEnabled(): Boolean {
        return true
    }
}
